package com.zy.mc_module.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zy.mc_module.R;

import java.util.ArrayList;
import java.util.List;

/***
 * Created on 2019/04/14
 * 自定义支付密码View
 */
public class PaymentView extends RelativeLayout {

    Context context;
    private LinearLayout linear_pass;
    //private TextView tv_complete;//完成
    private TextView[] tvList; // 就6个输入框不会变了，用数组内存申请固定空间，比List省空间
    private GridView gridView; // 用GrideView布局键盘，其实并不是真正的键盘，只是模拟键盘的功能
    private List<String> numList;//键盘的数字
    private String[] letters;//键盘的字母
    private int currentIndex = -1; // 用于记录当前输入密码格位置
    private String strPassword = ""; // 输入的密码

    public PaymentView(Context context) {
        this(context, null);
    }

    public PaymentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initView();
        initAttr(context, attrs);
    }

    private void initView() {
        letters = new String[]{"", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ", "", "", ""};
        //view布局
        View view = View.inflate(context, R.layout.layout_payment, null);
        numList = new ArrayList<>();
        tvList = new TextView[6];
        //初始化控件
        tvList[0] = view.findViewById(R.id.tv_pass1);
        tvList[1] = view.findViewById(R.id.tv_pass2);
        tvList[2] = view.findViewById(R.id.tv_pass3);
        tvList[3] = view.findViewById(R.id.tv_pass4);
        tvList[4] = view.findViewById(R.id.tv_pass5);
        tvList[5] = view.findViewById(R.id.tv_pass6);
        gridView = view.findViewById(R.id.gv_keybord);
        linear_pass = view.findViewById(R.id.linear_pass);
        //tv_complete = view.findViewById(R.id.tv_complete);
        //设置键盘按钮显示内容
        setView();
        //添加控件
        this.addView(view);
    }

    private void initAttr(Context context, AttributeSet attrs) {
        if (null != attrs) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PaymentView);
            //是否是弹框模式
            boolean isDialog = typedArray.getBoolean(R.styleable.PaymentView_isDialog, false);
            float margin_bom = typedArray.getDimension(R.styleable.PaymentView_margin_bom, dp2px(70));

            LayoutParams params = new LayoutParams(-1, -2);
            if (isDialog) {
                //弹框显示
                //tv_complete.setVisibility(GONE);
                params.addRule(RelativeLayout.BELOW, R.id.linear_pass);
                //-----
                LayoutParams paramss = new LayoutParams(-1, dp2px(55));
                paramss.setMargins(dp2px(16), 0, dp2px(16), (int) margin_bom);
                linear_pass.setLayoutParams(paramss);
            } else {
                //Activity显示
                //tv_complete.setVisibility(VISIBLE);
                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                params.setMargins(0, 0, 0, 0);
            }
            gridView.setLayoutParams(params);
            typedArray.recycle();
        }
    }

    /***
     *  设置按钮显示内容
     */
    private void setView() {
        // 初始化按钮上应该显示的数字
        for (int i = 1; i < 13; i++) {
            if (i < 10) {
                numList.add(String.valueOf(i));
            } else if (i == 10) {
                numList.add("");//左下角
            } else if (i == 11) {
                numList.add(String.valueOf(0));
            } else if (i == 12) {
                numList.add("");//右下角-删除
            }
        }
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener((parent, view, position, id) -> {
            // 点击0~9按钮
            if (position < 11 && position != 9) {
                // 判断输入位置————要小心数组越界
                if (currentIndex >= -1 && currentIndex < 5) {
                    tvList[++currentIndex].setText(numList.get(position));
                }
            } else {
                // 点击退格键
                if (position == 11) {
                    // 判断是否删除完毕————要小心数组越界
                    if (currentIndex - 1 >= -1) {
                        tvList[currentIndex--].setText("");
                        //刷新密码
                        refreshPwd();
                    }
                }
            }
        });
    }

    /***
     * 设置监听方法，在第6位输入完成后触发
     * @param onPassInputFinish
     */
    public void setOnFinishInput(OnPassInputFinish onPassInputFinish) {
        //最后一个密码框的监听
        tvList[5].addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 1) {
                    //刷新密码
                    refreshPwd();
                    //如果需要自动处理,就这这里暴露接口
                    onPassInputFinish.inputFinish(strPassword, true);
                }
            }
        });

        //输入密码完成
        //tv_complete.setOnClickListener(v -> onPassInputFinish.inputFinish(strPassword, false));
    }

    /***
     * GrideView的适配器
     */
    BaseAdapter adapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return numList.size();
        }

        @Override
        public Object getItem(int position) {
            return numList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                //装载数字键盘布局
                convertView = View.inflate(context, R.layout.item_keyboard, null);
                holder = new ViewHolder();
                //初始化键盘按钮
                holder.iv_del = convertView.findViewById(R.id.keys_del);
                holder.tv_num = convertView.findViewById(R.id.keys_num);
                holder.keys_root = convertView.findViewById(R.id.keys_root);
                holder.tv_letter = convertView.findViewById(R.id.keys_letter);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            //设置按钮显示数字
            holder.tv_num.setText(numList.get(position));
            holder.tv_letter.setText(letters[position]);
            if (position == 9) {
                //左下角的按钮显示空白,不做任何处理,不能点击
                holder.keys_root.setEnabled(false);
                holder.keys_root.setBackgroundColor(Color.parseColor("#e6e6e6"));
            }
            if (position == 11) {
                //右下角按钮,删除左右,设置删除按钮和背景
                holder.iv_del.setVisibility(VISIBLE);
                holder.keys_root.setBackgroundColor(Color.parseColor("#e6e6e6"));
            }
            return convertView;
        }
    };

    public final class ViewHolder {
        public ImageView iv_del;
        public RelativeLayout keys_root;
        public TextView tv_num, tv_letter;
    }

    /***
     * 刷新输入的密码
     */
    public void refreshPwd() {
        strPassword = "";
        for (int i = 0; i < 6; i++) {
            strPassword += tvList[i].getText().toString().trim();
        }
        //if (null != strPassword && strPassword.length() == 6) {
        //    tv_complete.setEnabled(true);
        //} else {
        //    tv_complete.setEnabled(false);
        //}
    }

    /***
     * 获取输入的密码
     */
    public String getStrPassword() {
        return strPassword;
    }

    /***
     * 清除输入的密码
     */
    public void clearPwd() {
        new Handler().postDelayed(() -> {
            strPassword = "";
            currentIndex = -1;
            for (int i = 0; i < 6; i++) {
                tvList[i].setText("");
            }
            //if (null != strPassword && strPassword.length() == 6) {
            //    tv_complete.setEnabled(true);
            //} else {
            //    tv_complete.setEnabled(false);
            //}
        }, 120);
    }

    public interface OnPassInputFinish {
        /***
         * 添加密码输入完成的接口
         * @param password  密码
         * @param isAuto  自动处理,不需要点击确认按钮
         */
        void inputFinish(String password, boolean isAuto);
    }

    private int dp2px(float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
